#!/usr/bin/env python
# -*- coding: utf-8 -*-


from optparse import OptionParser
from sys import *
from subprocess import Popen
import re
import os.path
import pkgparser

#TODO: move to config file
#configuration
mirror = "ftp://ftp.slackware.pl/pub/slackware/slackware-13.0/"
cachedirectory = '/tmp/cache/pkgmanager/'
pkgdirectory = '/tmp/cache/pkgmangager/pkgacache/'

def addDep(pkg, pkglist):
    regex = '^' + pkg
    for line in depfile:
	if re.search(regex, line):
	    dependencies = re.sub(pkg + ':', '', line)
	    dependencies = re.sub(r'\n', '', dependencies)
	    dependencies = re.split(' ', dependencies)
	    pkglist.extend(dependencies)
    depfile.seek(0)
    return pkglist

def getPkg(pkg):
    #TODO: add md5 check
    linenr = pkgparser.findLine(pkg)
    pkgline = pkgparser.readPkgLocation(linenr)
    pkgfile = mirror + re.sub(r'\n', '', pkgline)
    wget = Popen(['wget', pkgfile], cwd=pkgdirectory)
    wget.wait()
    return pkgparser.readPkgFile(linenr)
	    
def installPkg(pkglist):
    pkglist = checkIfInstaled(pkglist)
    #pkglist = checkDep(pkglist)   
    for pkg in pkglist:
	pkgfile = getPkg(pkg)
	install = Popen(['installpkg', pkgfile], cwd=pkgdirectory)
	install.wait()
    

def removePkg(pkglist):
    for pkg in pkglist:
	remove = Popen(['removepkg', pkg])
	remove.wait()

#checkse dependecies for given list of packages
def checkDep(pkglist):
    depfile = open('depfile.txt', 'r')
    for pkg in pkglist:
	addDep(pkg, pkglist)
    return pkglist 

def printHelp():
    print "help"
    
def update():
    #TODO: error dosen't get killd whit pkgmanager
    #if FILELIST.TXT allready exist rm it before downloading
    wgetfile = mirror + 'FILELIST.TXT'
    wget = Popen(['wget', wgetfile])
    print("Procesing FILELIST.TXT")
    wget.wait()
    filelist = open("FILELIST.TXT", "r")
    pkglistfile = open('pkglist.txt', 'r')
    for line in filelist:
        if re.search('.txz$', line) and re.search('/(slackware|extra)/', line):
	    #TODO: find beter solution
	    line = re.sub(r'-rw-r--r-- +1 +(root +)+[0-9]* +([0-9]*-)+[0-9]* +[0-9]*:[0-9]* +.', r'', line)
	    splitline = re.split(r'/', line)
            if splitline[1] == 'extra':
		#TODO: fix problem with aspell-world-list
		pkgname = splitline[2]
		pkgfile = re.sub(r'\n', '', splitline[3])
		writeline = pkgname + ' ' + pkgfile + ' ' + line 
		pkglistfile.write(str(writeline))
	    elif splitline[1] == 'slackware':
		#error: some of pkgname end with version number
		found = re.search(r'([A-Za-z0-9_]*-)+', line)
		pkgname = re.sub(r'-$', '', found.group(0))
		pkgfile = re.sub(r'\n', '', splitline[3])
		writeline = pkgname + ' ' + pkgfile + ' ' + line 
		pkglistfile.write(str(writeline))
    filelist.close()
    print("Finished procesing")

def search(pkglist):
    #TODO: make better algorithm for searching of pkgline
    for pkg in pkglist:
        linenr = pkgparser.findLine(pkg)
	if linenr:
	    print pkgparser.readPkgFile(linenr)
	else:
	    print 'Not found'


def checkIfInstaled(pkglist):
    #checks if pkg is installed and removes from pkglist
    for pkg in pkglist:
	linenr = pkgparser.findLine(pkg)
	pkgfile = pkgparser.readPkgFile(linenr)
	filename = re.sub( r'.txz', r'', pkgfile)
	filename = os.path.join('/var/log/packages', filename)
	if os.path.exists(filename):
	    print pkg + ' allready installed, ommiting'
	    pkglist.remove(pkg)
    return pkglist

def upgrade(pkglist):
    #TODO:
    pass

def upgradeAll():
    #TODO:
    pass

#TODO: exception handel if no arguments are passed or too few
command = argv[1]
pkglist = argv[2:]


if command == "install":
    installPkg(pkglist)
elif command == "remove":
    removePkg(pkglist)
elif command == "update":
    update()
elif command == "search":
    search(pkglist)
elif command == "upgrade":
    upgrade(pkglist)
elif command == "upgrade-all":
    upgradeAll()
else:
    printHelp()
    